<?php

/**
 * @author PhuTang, PhatPham
 * @copyright 2013
 */

class Survey extends CI_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->model('Surveymodel'); // Load model
        $this->load->model('Questionmodel'); // Load model
        $this->load->model('AnswerTemplatemodel'); // Load model
        $this->load->model('Informodel'); // Load model
        $this->load->model('SurveyTypemodel'); // Load model
        $this->load->model('DesignTemplatemodel'); // Load model
		$this->load->model('AnswerRelationmodel'); // Load model
		$this->load->model('Provincemodel');
        $this->load->helper(array('form', 'url', 'date')); // Load helper url
        $this->load->library(array('session', 'form_validation')); //Load lib session
    }

    //Surveys list-------------------------------------------------------------------------------------
	//Author: PhatPham
    public function index($stid){
        //Check whether empty
        if (!empty($stid)) {
            //get action
            $button = $this->input->post('submit');
            //Delete survey action
            if ($button=="delete"){
                $sid = $this->input->post('sid');
                $this->delete($sid);
            }

            //Get surveys list from model
            $data['slist'] = $this->Surveymodel->get_surveys_list($stid, null)->result();
            //Get survey type name from model
            $data['st'] = $this->SurveyTypemodel->get_survey_type($stid);
            //Set title for view
            $data['title'] = "Quản lý khảo sát";

            //Create session to store data
            $ssdata = array('survey_type_id' => $stid, 'survey_id' => '');
            $this->session->set_userdata($ssdata);

            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/List', $data);
            $this->load->view('Templates/Footer');
        }
    }

    //Create survey step 1----------------------------------------------------------------------------
	//Author: PhatPham
    public function create_step1(){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
		
        //Check whether empty
        if (!empty($stid)) {
            $data['check_duration'] = '';
            //Get button value
            $button = $this->input->post('submit');
			
            //Next action
            if ($button=='next') {
				//Create session to store data
				$ssdata = array('survey_id' => '');
				$this->session->set_userdata($ssdata);
			
                //get isgraduated value
                $isgrad = $this->input->post('isgrad');
                
                //Set form validation rules
                $this->form_validation->set_rules('sname', 'Tên phiếu khảo sát', 'trim|required|callback_check_unique_name|xss_clean');
                $this->form_validation->set_rules('rsid', 'Phiếu khảo sát được sử dụng lại', 'isset');
                $this->form_validation->set_rules('isvoc', 'Bậc', 'required');
                $this->form_validation->set_rules('isgrad', 'Đã tốt nghiệp', 'isset');
                if (empty($isgrad)){
                    $isgrad = FALSE;
                    $this->form_validation->set_rules('course', 'Khóa', 'required');
                }
                else{
                    $this->form_validation->set_rules('gyear', 'Năm tốt nghiệp', 'required');
                }
                $this->form_validation->set_rules('sdate', 'Ngày', 'required|callback_check_date_format|xss_clean');
                $this->form_validation->set_rules('edate', 'Ngày', 'required|callback_check_date_format|xss_clean');
                $this->form_validation->set_rules('iseval', 'Phiếu khảo sát này cần được đánh giá', 'isset');
                
				//If input data is valid
                if ($this->form_validation->run() == true) {
                    //Generate unique id
                    $sid = $this->unique_id();
                    //Get data from view
                    $rsid = $this->input->post('rsid');
                    $sname = $this->input->post('sname');
                    $course = $this->input->post('course');
                    $gyear = $this->input->post('gyear');
                    $sdate = $this->input->post('sdate');
                    $edate = $this->input->post('edate');
                    $isvoc = $this->input->post('isvoc');
                    $iseval = $this->input->post('iseval');
                    //Check if isevaluation is empty, set it false
                    if (empty($iseval)) $iseval = FALSE;
                    
                    //Check whether survey duration is not duplicated
                    $ck = $this->Surveymodel->check_survey_duration($sdate, $edate, null);
					//If not duplicated
                    if($ck == FALSE){
                        //Insert survey to db
                        if(empty($rsid))
                            $this->Surveymodel->create_survey($sid, null, $stid, $sname, $course, $gyear, $isgrad,
                                $sdate, $edate, $isvoc, null, null, '0', $iseval, null);
                        else{
                            $this->Surveymodel->create_survey($sid, $rsid, $stid, $sname, $course, $gyear, $isgrad,
                                $sdate, $edate, $isvoc, null, null, '0', $iseval, null);
                            //Copy questions list of reused survey
                            //Get questions list and answer templates list of each question from db
                            $qlist = $this->Questionmodel->get_questions_list($rsid)->result();
                            $i = 0;
                            $atlist = null;
                            foreach($qlist as $q)
                                $atlist[$i++] = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
                            
                            //Insert new question to db
                            $i = 0;
                            foreach($qlist as $q){
                                $qid = $this->unique_id();
                                $this->Questionmodel->create_question($qid, $q->question_id, $q->content, $q->view_order, $q->view_style, $q->max_option, $q->start_hide, $q->required, $q->is_validated, $q->is_evaluated, $sid, null);
                                foreach($atlist[$i++] as $at)
                                    $this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $at->option_type, $at->view_order, $at->label, $at->exception, $at->sub_question, null); 
                            }
                        }
        
						//Create session to store data
						$ssdata = array('survey_type_id' => $stid, 'survey_id' => $sid);
						$this->session->set_userdata($ssdata);
                        //Move to step 2
                        redirect('/survey/edit_step2');
                    }else
                        $data['check_duration'] = 'Thời gian áp dụng khảo sát bị trùng lặp.';
                }
            }
            //Get survey type from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
            //Get surveys list from model
            $slist = $this->Surveymodel->get_surveys_list($stid, null)->result();
			//Create courses and graduated years list
			$clist = null;
			$gylist = null;
			$syear = 1995; $eyear = date('Y');
			for($i=0; $i<$eyear-$syear; $i++){
				$clist[$i] = $i + 1;
				$gylist[$i] = $syear + $i + 4;
			}

            //Set data for view
            $data['title'] = "Thêm phiếu khảo sát - Bước 1";
            $data['st'] = $st;
            $data['slist'] = $slist;
			$data['clist'] = $clist;
			$data['gylist'] = $gylist;

            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Create_Step1', $data);
            $this->load->view('Templates/Footer');
        }
    }
    //Edit survey step 1---------------------------------------------------------------------------
	//Author: PhatPham
    public function edit_step1($sid){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
        //Check whether empty
        if (!empty($stid) & !empty($sid)) {
			$data['check_duration'] = '';
            //Get button value
            $button = $this->input->post('submit');
            //Check whether submit
            if ($button == 'next') {
				//Create session to store data
				$ssdata = array('survey_id' => $sid);
				$this->session->set_userdata($ssdata);
			
				//get isgraduated value
                $isgrad = $this->input->post('isgrad');
                
                //Set form validation rules
                $this->form_validation->set_rules('sname', 'Tên phiếu khảo sát', 'trim|required|callback_check_unique_name|xss_clean');
                $this->form_validation->set_rules('rsid', 'Phiếu khảo sát được sử dụng lại', 'isset');
                $this->form_validation->set_rules('isvoc', 'Bậc', 'required');
                $this->form_validation->set_rules('isgrad', 'Đã tốt nghiệp', 'isset');
                if (empty($isgrad)){
                    $isgrad = FALSE;
                    $this->form_validation->set_rules('course', 'Khóa', 'required');
                }
                else{
                    $this->form_validation->set_rules('gyear', 'Năm tốt nghiệp', 'required');
                }
                $this->form_validation->set_rules('sdate', 'Ngày', 'required|callback_check_date_format|xss_clean');
                $this->form_validation->set_rules('edate', 'Ngày', 'required|callback_check_date_format|xss_clean');
                $this->form_validation->set_rules('iseval', 'Phiếu khảo sát này cần được đánh giá', 'isset');
                
				//If input data is valid
                if ($this->form_validation->run() == true) {
					//Get data from view
					$rsid = $this->input->post('rsid');
					$sname = $this->input->post('sname');
					$course = $this->input->post('course');
					$gyear = $this->input->post('gyear');
					$isgrad = $this->input->post('isgrad');
					$sdate = $this->input->post('sdate');
					$edate = $this->input->post('edate');
					$isvoc = $this->input->post('isvoc');
					$iseval = $this->input->post('iseval');

					//Check whether data is empty
					if (empty($isgrad))
						$isgrad = FALSE;
					if (empty($iseval))
						$iseval = FALSE;

					//Check whether survey duration is not duplicated
                    $ck = $this->Surveymodel->check_survey_duration($sdate, $edate, $sid);
					//If not duplicated
                    if($ck == FALSE){
						//Get current survey from model
						$cs = $this->Surveymodel->get_survey($sid);
						//Delete all questions of current survey if reuse new survey
						if($cs->reused_survey_id != $rsid){
							//get question id
							$qlist = $this->Questionmodel->get_questions_list($sid)->result();
							//Delete all questions of current survey
							if (!empty($sid)) {
								foreach($qlist as $q)
									$this->AnswerTemplatemodel->delete_question_answer_templates($q->question_id,null);
							}
							$this->Questionmodel->delete_survey_questions($sid,null);
							
							//Copy questions list of new reused survey
                            //Get questions list and answer templates list of each question from db
                            $qlist = $this->Questionmodel->get_questions_list($rsid)->result();
                            $i = 0;
                            $atlist = null;
                            foreach($qlist as $q)
                                $atlist[$i++] = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
                            
                            //Insert new question to db
                            $i = 0;
                            foreach($qlist as $q){
                                $qid = $this->unique_id();
                                $this->Questionmodel->create_question($qid, $q->question_id, $q->content, $q->view_order, $q->view_style, $q->max_option, $q->start_hide, $q->required, $q->is_validated, $q->is_evaluated, $sid, null);
                                foreach($atlist[$i++] as $at)
                                    $this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $at->option_type, $at->view_order, $at->label, $at->exception, $at->sub_question, null); 
                            }
						}
						
						//Edit survey information to model
						if(empty($rsid))
							$this->Surveymodel->edit_survey_1($sid, null, $stid, $sname, $course, $gyear, $isgrad,
								$sdate, $edate, $isvoc, $iseval, null);
						else
							$this->Surveymodel->edit_survey_1($sid, $rsid, $stid, $sname, $course, $gyear, $isgrad,
								$sdate, $edate, $isvoc, $iseval, null);
						
						//Create session to store data
						$ssdata = array('survey_type_id' => $stid, 'survey_id' => $sid);
						$this->session->set_userdata($ssdata);
						//Move to step 2
						redirect('/survey/edit_step2');
					}else
                        $data['check_duration'] = 'Thời gian áp dụng khảo sát bị trùng lặp.';
				}
            }
            //Get survey type from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
			//Get survey from model
			$survey = $this->Surveymodel->get_survey($sid);
            //Get surveys list from model
            $slist = $this->Surveymodel->get_surveys_list($stid, $sid)->result();
			//Create courses and graduated years list
			$clist = null;
			$gylist = null;
			$syear = 1995; $eyear = date('Y');
			for($i=0; $i<$eyear-$syear; $i++){
				$clist[$i] = $i + 1;
				$gylist[$i] = $syear + $i + 4;
			}
            //Convert sqlserver time format SS format
            $survey->start_date = mdate('%m/%d/%Y', strtotime($survey->start_date));
            $survey->end_date = mdate('%m/%d/%Y', strtotime($survey->end_date));
            
            //Set data for view
            $data['title'] = "Sửa phiếu khảo sát - Bước 1";
            $data['st'] = $st;
			$data['survey'] = $survey;
            $data['slist'] = $slist;
            $data['clist'] = $clist;
			$data['gylist'] = $gylist;

            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Edit_Step1', $data);
            $this->load->view('Templates/Footer');
        }
    }
	//Edit survey step 2----------------------------------------------------------------------------
	public function edit_step2(){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
        //Get survey id from session
        $sid = $this->session->userdata('survey_id');
        //Check whether empty
        if (!empty($stid) && !empty($sid)) {
            //Get button value
            $button = $this->input->post('submit');
            //Check whether submit
            if (!empty($button)) {
                if ($button == 'next') {
					//set form validation rules
					$this->form_validation->set_rules('dtid', 'Khung nhập thông tin', 'required');
						
					if($this->form_validation->run() == true){
						//Get data from view
						$dtid = $this->input->post('dtid');
						//Edit survey to db
						$this->Surveymodel->edit_survey_2($sid, $dtid, null);

						//Create session to store survey type id
						$ssdata = array('survey_type_id' => $stid, 'survey_id' => $sid);
						$this->session->set_userdata($ssdata);

						//Move to step 3
						redirect('/survey/edit_step3');
					}
                }
            }
            //Get survey type from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
            //Get design templates list from model
            $dtlist = $this->DesignTemplatemodel->get_design_templates_list()->result();
            //Get survey
            $survey = $this->Surveymodel->get_survey($sid);

            //Set data for view
            $data['title'] = "Sửa phiếu khảo sát - Bước 2";
            $data['st'] = $st;
            $data['dtlist'] = $dtlist;
            $data['survey'] = $survey;

            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Edit_Step2', $data);
            $this->load->view('Templates/Footer');
        }
    }
    public function edit_step3(){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
        //Get survey id from session
        $sid = $this->session->userdata('survey_id');
        //Check whether empty
        if (!empty($stid) && !empty($sid)) {
            $data['check_number_of_answer_templates'] = '';
            //Get button value
            $button = $this->input->post('submit');
            //Add question action
            if ($button == 'addquestion') {
                //set form validation rules
                $this->form_validation->set_rules('content', 'Câu hỏi', 'trim|required|max_length[500]|xss_clean');
                $this->form_validation->set_rules('vorder', 'Thứ tự sắp xếp', 'required');
                $this->form_validation->set_rules('otype', 'Dạng câu trả lời', 'required');
                $this->form_validation->set_rules('vstyle', 'Cách thể hiện', 'required');
                
                if($this->form_validation->run() == true){
                    //generate question id
                    $qid = $this->unique_id();
                    //Get data from view
                    $content = $this->input->post('content');
                    $required = $this->input->post('required');
					$shide = $this->input->post('shide');
                    $vorder = $this->input->post('vorder');
                    //Change view order of other questions
                    $qlist = $this->Questionmodel->get_questions_list_after($sid, $vorder);
                    if($qlist->num_rows() > 0)
                        foreach($qlist->result() as $q)
                            $this->Questionmodel->edit_question_view_order($q->question_id, $q->view_order+1, null);
                    
                    $otype = $this->input->post('otype');
                    $vstyle = $this->input->post('vstyle');
                    $labels = $this->input->post('labels');
					$otypes = $this->input->post('otypes');
					//Count input answer templates
                    $maxopt = 0; if(!empty($labels)) foreach($labels as $label) $maxopt++;
                    
                    if($maxopt > 1 || ($maxopt == 1 && $otype == 't')){
                        //Add question to db
                        $this->Questionmodel->create_question($qid, null, $content, $vorder, $vstyle, $maxopt, $shide, $required, FALSE, FALSE, $sid, null);
                        //add answer templates of question to db
                        $atvorder=1;
                        foreach($labels as $label){
                            $this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $otypes[$atvorder-1], $atvorder, $label, null, FALSE, null);
							$atvorder++;
						}
						
						//Add answer relation if the other questions has links-----------------------------
						//Get questions list of survey
						$qs = $this->Questionmodel->get_questions_list_before($sid, $vorder)->result();
						foreach($qs as $q){
							//Get answer templates of question at $i
							$ats = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
							foreach($ats as $at){
								//Get answer relations of answer template at $j
								$ars = $this->AnswerRelationmodel->get_answer_relations_list($at->template_id);
								//Check if ars is not empty, create answer relation
								if($ars->num_rows() != 0)
									$this->AnswerRelationmodel->create_answer_relation($at->template_id, $qid, TRUE, null);
							}
						}
                    }else
                        $data['check_number_of_answer_templates'] = 'Bạn chưa thêm câu trả lời.';
                }
            }
            //Next to step 4
            else if($button == 'next'){
                //Create session to store survey type id
                $ssdata = array('survey_type_id' => $stid, 'survey_id' => $sid);
                $this->session->set_userdata($ssdata);

                //Move to step 4
                redirect('/survey/edit_step4');
            }
            //Delete question action
            else if($button == 'deletequestion'){
                //Get question id want to delete
                $qid = $this->input->post('deleteqid');
                //Get question from db;
                $q = $this->Questionmodel->get_question($qid);
                
                //Change view order of other questions
                $qlist = $this->Questionmodel->get_questions_list_after($sid, $q->view_order);
                if($qlist->num_rows() > 0)
                    foreach($qlist->result() as $q)
                        $this->Questionmodel->edit_question_view_order($q->question_id, $q->view_order-1, null);
                
                //Call delete question function
                $this->delete_question($qid);
            }
            //Duplicate question action
            else if($button == 'duplicatequestion'){
                //Get quetions list of survey
                $qlist = $this->Questionmodel->get_questions_list($sid);
                //Get question id want to duplicate
                $qid = $this->input->post('duplicateqid');
                //Get question from db
                $q = $this->Questionmodel->get_question($qid);
                //Create new question
                $newqid = $this->unique_id();
                $this->Questionmodel->create_question($newqid, null, $q->content, $qlist->num_rows()+1, $q->view_style, $q->max_option, FALSE, $q->required, FALSE, FALSE, $q->survey_id, null);
                
                //get answer templates list of question from db
                $atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
                //Create new answer template
                foreach($atlist as $row)
                    $this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $newqid, $row->option_type, $row->view_order, $row->label, $row->exception, $row->sub_question, null);
					
				//Add answer relation if the other questions has links-----------------------------
				//Get questions list of survey
				$qs = $this->Questionmodel->get_questions_list_before($sid, $qlist->num_rows()+1)->result();
				foreach($qs as $q){
					//Get answer templates of question at $i
					$ats = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
					foreach($ats as $at){
						//Get answer relations of answer template at $j
						$ars = $this->AnswerRelationmodel->get_answer_relations_list($at->template_id);
						//Check if ars is not empty, create answer relation
						if($ars->num_rows() != 0){
							echo 
							$this->AnswerRelationmodel->create_answer_relation($at->template_id, $newqid, TRUE, null);
						}
					}
				}
            }
            
            //Get survey type from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
			//get survey from model
			$survey = $this->Surveymodel->get_survey($sid);
            //Get questions list of survey
            $qlist = $this->Questionmodel->get_questions_list($sid);
			//Get provinces list
			$prlist = $this->Provincemodel->get_provinces_list();
			
            //Set data for view
            $data['title'] = "Thêm phiếu khảo sát - Bước 3";
            $data['st'] = $st;
			$data['survey'] = $survey;
            $data['vorder'] = $qlist->num_rows();
            $data['qlist'] = $qlist->result();
            $i=0;
            $atlist = null;
            foreach($qlist->result() as $q)
                $atlist[$i++] = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
            $data['atlist'] = $atlist;
			$data['prlist'] = $prlist->result();
			
            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Edit_Step3', $data);
            $this->load->view('Templates/Footer');
        }
    }
	public function edit_step4(){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
        //Get survey id from session
        $sid = $this->session->userdata('survey_id');
        //Check whether empty
        if (!empty($stid) && !empty($sid)) {
            //Get button value
            $button = $this->input->post('submit');
            //Add question action
            if ($button == 'submit') {
                //Get questions list of survey
                $qlist = $this->Questionmodel->get_questions_list($sid)->result();
                //Get is_validated list from view
                $isvallist = $this->input->post('isvals');
                //Get is_evalated list from view
                $isevallist = $this->input->post('isevals');
                //Update isvalidated and isevaluated of question
                $i = 0;
                foreach($qlist as $q){
					$isval = $isvallist[$i] == null ? FALSE : TRUE;
					$iseval = $isevallist[$i] == null ? FALSE : TRUE;
                    $this->Questionmodel->edit_question_validated($q->question_id, $isval, null);
                    $this->Questionmodel->edit_question_evaluated($q->question_id, $iseval, null);
                    $i++;
                }
				
				//Create session to store survey type id
                $ssdata = array('survey_type_id' => $stid, 'survey_id' => '');
                $this->session->set_userdata($ssdata);

                //Move to survey details
                redirect('/survey/details/'.$sid);
            }
            
            //Get survey type from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
            //Get survey
            $survey = $this->Surveymodel->get_survey($sid);
            //Get questions list of survey
            $qlist = $this->Questionmodel->get_questions_list($sid);

            //Set data for view
            $data['title'] = "Thêm phiếu khảo sát - Bước 4";
            $data['st'] = $st;
            $data['survey'] = $survey;
            $data['qlist'] = $qlist->result();
			$data['maxq'] = $qlist->num_rows();
			
            $i=0;
            $atlist = null;
			$arlist = null;
			$linklist = null;	//Nếu câu hỏi có liên kết -> true
            foreach($qlist->result() as $q){
				//Get answer templates of question at $i
				$ats = $this->AnswerTemplatemodel->get_answer_templates_list($q->question_id)->result();
                $atlist[$i] = $ats;
				
				$j=0;
				$ars = null;
				foreach($ats as $at){
					//Get answer relations of answer template at $j
					$query = $this->AnswerRelationmodel->get_answer_relations_list($at->template_id);
					$ars[$j] = $query->result();
					
					$linklist[$i] = $query->num_rows() == 0 ? FALSE : TRUE;
					$j++;
				}
				$arlist[$i] = $ars;
				$i++;
            }
            $data['atlist'] = $atlist;
			$data['arlist'] = $arlist;
			$data['linklist'] = $linklist;
			
            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Edit_Step4', $data);
            $this->load->view('Templates/Footer');
        }
    }

    //Edit question--------------------------------------------------------------------
    public function edit_question($qid){
        //Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
        //Get survey id from session
        $sid = $this->session->userdata('survey_id');
        //Check whether empty
        if (!empty($stid) && !empty($sid) && !empty($qid)) {
            $data['check_number_of_answer_templates'] = '';
			//Get button value
            $button = $this->input->post('submit');
            //Add question action
            if ($button == 'submit') {
                //set form validation rules
                $this->form_validation->set_rules('content', 'Câu hỏi', 'trim|required|max_length[500]|xss_clean');
                $this->form_validation->set_rules('vorder', 'Thứ tự sắp xếp', 'required');
                $this->form_validation->set_rules('otype', 'Dạng câu trả lời', 'required');
                $this->form_validation->set_rules('vstyle', 'Cách thể hiện', 'required');
                
                if($this->form_validation->run() == true){
                    //Get data from view
                    $content = $this->input->post('content');
                    $required = $this->input->post('required');
					$shide = $this->input->post('shide');
                    $vorder = $this->input->post('vorder');
                    $otype = $this->input->post('otype');
                    $vstyle = $this->input->post('vstyle');
                    $labels = $this->input->post('labels');
                    $otypes = $this->input->post('otypes');
					//Count input answer templates
					$maxopt = 0; if(!empty($labels)) foreach($labels as $label) $maxopt++;
                    
					if($maxopt > 1 || ($maxopt == 1 && $otype == 't')){
						//Get old question
						$oldq = $this->Questionmodel->get_question($qid);
						//Get answer templates of old question
						$oldatlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid);
						//Get max option of old question
						$oldmaxopt = $oldatlist->num_rows();
						$oldatlist = $oldatlist->result();
						
						//Change view order of other questions
						if($vorder > $oldq->view_order){
							//Get questions list from to
							$qlist = $this->Questionmodel->get_questions_list_from_to($sid, $oldq->view_order, $vorder);
							if($qlist->num_rows() > 0)
								foreach($qlist->result() as $q)
									if($q->question_id != $qid){
										//Changes view order of other questions
										$this->Questionmodel->edit_question_view_order($q->question_id, $q->view_order-1, null);
										//Delete answer relations
										if($oldatlist[0]->option_type == 'r ' && $otype == 'r' && $oldmaxopt == $maxopt)
											foreach($oldatlist as $at)
												$this->AnswerRelationmodel->delete_answer_relation($at->template_id, $q->question_id);
									}
						}else{
							//Get questions list from to
							$qlist = $this->Questionmodel->get_questions_list_from_to($sid, $vorder, $oldq->view_order);
							if($qlist->num_rows() > 0)
								foreach($qlist->result() as $q)
									if($q->question_id != $qid){
										//Changes view order of other questions
										$this->Questionmodel->edit_question_view_order($q->question_id, $q->view_order+1, null);
										//Create answer relations
										if($oldatlist[0]->option_type == 'r ' && $otype == 'r' && $oldmaxopt == $maxopt)
											foreach($oldatlist as $at){
												//Get answer relations of answer template
												$arlist = $this->AnswerRelationmodel->get_answer_relations_list($at->template_id);
												if($arlist->num_rows() > 0)
													$this->AnswerRelationmodel->create_answer_relation($at->template_id, $q->question_id, TRUE, null);
											}
									}
						}
						
						//Edit answer templates and answer relations
						//Option type is changed to 'c', 't' or 'pr'
						if(	($oldatlist[0]->option_type == 'r ' && $otype != 'r') || 
							($oldatlist[0]->option_type != 'r ' && $otype != 'r')){
							//Delete all answer relations
							foreach($oldatlist as $at)
								$this->AnswerRelationmodel->delete_answer_relations_list($at->template_id);
							//Delete old answer templates
							$this->AnswerTemplatemodel->delete_question_answer_templates($qid, null);
							//Create new answer templates
							$atvorder=1;
							foreach($labels as $label){
								$this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $otypes[$atvorder-1], $atvorder, $label, null, FALSE, null);
								$atvorder++;
							}
						}
						//Option type is changed to 'r'
						else if($oldatlist[0]->option_type != 'r ' && $otype == 'r'){
							//Delete old answer templates
							$this->AnswerTemplatemodel->delete_question_answer_templates($qid, null);
							//Create new answer templates
							$atvorder=1;
							foreach($labels as $label){
								$this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $otypes[$atvorder-1], $atvorder, $label, null, FALSE, null);
								$atvorder++;
							}
						}
						//Option type is not changed
						else if($oldatlist[0]->option_type == 'r ' && $otype == 'r'){
							//Max option is not changed
							if($oldmaxopt == $maxopt){
								//Edit answer templates
								$i=0;
								foreach($oldatlist as $at){
									$this->AnswerTemplatemodel->edit_answer_template($at->template_id, $otypes[$i], $at->view_order, $labels[$i], $at->exception, $at->sub_question, null);
									$i++;
								}
							}
							//Max option is changed
							else{
								//Delete all answer relations
								foreach($oldatlist as $at)
									$this->AnswerRelationmodel->delete_answer_relations_list($at->template_id);
								//Delete old answer templates
								$this->AnswerTemplatemodel->delete_question_answer_templates($qid, null);
								//Create new answer templates
								$atvorder=1;
								foreach($labels as $label){
									$this->AnswerTemplatemodel->create_answer_template($this->unique_id(), $qid, $otypes[$atvorder-1], $atvorder, $label, null, FALSE, null);
									$atvorder++;
								}
								//Create new answer relations
								$atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
								$qlist = $this->Questionmodel->get_questions_list_after($sid, $vorder)->result();
								foreach($atlist as $at){
									//Get answer relations of answer template
									$arlist = $this->AnswerRelationmodel->get_answer_relations_list($at->template_id);
									if($arlist->num_rows() > 0)
										foreach($qlist as $q)
											$this->AnswerRelationmodel->create_answer_relation($at->template_id, $q->question_id, TRUE, null);
								}
							}
						}
						
						//Edit question
						$this->Questionmodel->edit_question($qid, $content, $vorder, $vstyle, $maxopt, $shide, $required, null);
						
						//Create session to store data
						$ssdata = array('survey_type_id' => $stid, 'survey_id' => $sid);
						$this->session->set_userdata($ssdata);
						//Move to step 3
						redirect('survey/edit_step3');
					}else
						$data['check_number_of_answer_templates'] = 'Bạn chưa thêm câu trả lời.';
                }
            }
            
            //Get survey type name from model
            $st = $this->SurveyTypemodel->get_survey_type($stid);
            //Get survey name from model
            $survey = $this->Surveymodel->get_survey($sid);
            //Get questions list of survey
            $qlist = $this->Questionmodel->get_questions_list($survey->survey_id);
            //Get question from model
            $q = $this->Questionmodel->get_question($qid);
            //Get answer templates list of question from model
            $atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
			//get provinces list
			$prlist = $this->Provincemodel->get_provinces_list()->result();

            //Set data for view
            $data['title'] = "Chỉnh sửa câu hỏi";
            $data['st'] = $st;
            $data['survey'] = $survey;
            
            $data['q'] = $q;
            $data['maxq'] = $qlist->num_rows();
            $data['otype'] = $atlist[0]->option_type;
            $data['atlist'] = $atlist;
			$data['prlist'] = $prlist;
            
            //Load view
            $this->load->view('Templates/Header', $data);
            $this->load->view('Survey/Edit_Question', $data);
            $this->load->view('Templates/Footer');
        }
    }
    //Survey details-----------------------------------------------------------------------
    public function details($sid){
		//Get survey type id from session
        $stid = $this->session->userdata('survey_type_id');
		
		if(!empty($sid)){
			//Get action
			$button = $this->input->post('submit');
			//delete action
			if($button == 'delete'){
				$this->delete($sid);
			}
			//close action
			else if($button == 'close'){
				$this->Surveymodel->edit_survey_status($sid, '2', null);
			}
			//open action
			else if($button == 'open'){
				$this->Surveymodel->edit_survey_status($sid, '1', null);
			}
		
			//Get survey type
			$st = $this->SurveyTypemodel->get_survey_type($stid);
			//Get survey
			$survey = $this->Surveymodel->get_survey($sid);
			$survey->start_date = mdate('%m/%d/%Y', strtotime($survey->start_date));
			$survey->end_date = mdate('%m/%d/%Y', strtotime($survey->end_date));
			
			//Set data for view
			$data['title'] = $survey->survey_name;
			$data['st'] = $st;
			$data['survey'] = $survey;
			//Load view
			$this->load->view('Templates/Header', $data);
			$this->load->view('Survey/Details', $data);
			$this->load->view('Templates/Footer');
		}
    }
    //Delete survey
    private function delete($sid){
		//get question id
        $qlist = $this->Questionmodel->get_questions_list($sid)->result();
        //Check whether empty
        if (!empty($sid)) {
            foreach($qlist as $q)
            {
                $qid = $q->question_id;
				//Get answer templates of question
				$atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
				foreach($atlist as $at){
					//Delete answer relation
					$this->AnswerRelationmodel->delete_answer_relations_list($at->template_id);
				}
				//Delete answer template
                $this->AnswerTemplatemodel->delete_question_answer_templates($qid,null);    
            }
        }
		//delete question
        $this->Questionmodel->delete_survey_questions($sid,null);
		//delete survey
        $this->Surveymodel->delete_survey($sid, null);
    }
    //Delete question--------------------------------------------------------------------
    private function delete_question($qid){
		//Get answer templates of question
		$atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
		foreach($atlist as $at){
			//Delete answer relation
			$this->AnswerRelationmodel->delete_answer_relations_list($at->template_id);
		}
        //Delete answer templates of question
        $this->AnswerTemplatemodel->delete_question_answer_templates($qid,null);
        //Delete question
        $this->Questionmodel->delete_question($qid,null);
    }

    //Gererate unique survey type id with format---------------------------------------
    //xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx with x is from 0 to 9
    private function unique_id(){
        $this->load->helper('string');
        $id = random_string('numeric', 8) . '-' . random_string('numeric', 4) . '-' .
            random_string('numeric', 4) . '-' . random_string('numeric', 4) . '-' .
            random_string('numeric', 12);
        return $id;
    }
	//Check functions------------------------------------------------------------------
	//Author: PhatPham
	//Check survey for deleting; false->can't delete; used by Survey List view
    public function check_delete($sid){
        $s = $this->Surveymodel->get_survey($sid);
        if($s != null){
            if($s->status == '0'){
				echo TRUE;
			}else{
				$ilist = $this->Informodel->get_infors_list($sid);
				echo $ilist->num_rows() == 0 ? TRUE : FALSE;
			}
		}else
			echo FALSE;
    }
	//Author:PhatPham
    //Check valid date format for creating survey;
    public function check_date_format($date){
        $arr = explode('/', $date);
        if(checkdate ($arr[0], $arr[1], $arr[2])) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_date_format', 'Cấu trúc ngày không đúng. VD: 03/26/2013');
            return FALSE;
        }
    }
	//Author: PhatPham
	//Check unique survey name; false->exist name
	public function check_unique_name($sname){
		//Get survey type and survey id from session
		$stid = $this->session->userdata('survey_type_id');
		$sid = $this->session->userdata('survey_id');
		//Get surveys list from model exclude sid
		$slist = $this->Surveymodel->get_surveys_list($stid, $sid);
		//Check if input survey name is exist
		foreach($slist->result() as $s)
			if($s->survey_name == $sname){
				$this->form_validation->set_message('check_unique_name', 'Tên phiếu khảo sát đã tồn tại.');
				return FALSE;
			}
		return TRUE;
	}
    //Author: PhatPham
	//Add answer relations to question
	public function add_answer_relations_list($sid, $qid){
		//get question
		$question = $this->Questionmodel->get_question($qid);
		//get questions list after current question
		$qlist = $this->Questionmodel->get_questions_list_after($sid, $question->view_order + 1)->result();
		//Get answer templates of question
		$atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
		//Add answer relation of answer template and questions
		foreach($atlist as $at){
			foreach($qlist as $q)
				$this->AnswerRelationmodel->create_answer_relation($at->template_id, $q->question_id, TRUE, null);
		}
	}
	//Author: PhatPham
	//Edit answer relation value
	public function edit_answer_relation($atid, $qid, $attr){
		
		//edit value of answer relation
		$this->AnswerRelationmodel->edit_answer_relation_value($atid, $qid, $attr, null);
	}
	//Author: PhatPham
	//Delete answer relations of answer template
	public function delete_answer_relations_list($qid){
		//Get answer templates of question
		$atlist = $this->AnswerTemplatemodel->get_answer_templates_list($qid)->result();
		//Add answer relation of answer template and questions
		foreach($atlist as $at)
			$this->AnswerRelationmodel->delete_answer_relations_list($at->template_id);
	}
    //Ajax function-------------------------------------------------------------------
	//Add answer template for view
	public function add_answer_template($otype, $index){
		$data['otype'] = $otype;
        $data['index'] = $index;
		if($otype == 'pr')
			$data['prlist'] = $this->Provincemodel->get_provinces_list()->result();
        $this->load->view('Survey/Answer_Template', $data);
	}
}
?>
